package com.qding.park.manager.web.container;

import java.nio.charset.Charset;

import org.apache.catalina.connector.Connector;
import org.apache.coyote.http11.Http11NioProtocol;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.qding.park.manager.web.conf.MongoDatasourceConfigBean;
import com.qding.park.manager.web.conf.ServerConfig;

@Configuration
@Scope("singleton")
public class WebServerConfiguration {
	private static final Logger _log = LoggerFactory.getLogger(WebServerConfiguration.class);
	@Autowired
	private ServerConfig serverConfig;

	@Bean
	public EmbeddedServletContainerFactory createEmbeddedServletContainerFactory() {
		TomcatEmbeddedServletContainerFactory tomcatFactory = new TomcatEmbeddedServletContainerFactory();
		_log.info("port={},uriEncoding={}" + serverConfig.getPort(),serverConfig.getUriEncoding());
		tomcatFactory.setPort(serverConfig.getPort());
		tomcatFactory.addConnectorCustomizers(new MyTomcatConnectorCustomizer());
		tomcatFactory.setUriEncoding(Charset.forName(serverConfig.getUriEncoding()));
		return tomcatFactory;
	}

	class MyTomcatConnectorCustomizer implements TomcatConnectorCustomizer {
		public void customize(Connector connector) {
			Http11NioProtocol protocol = (Http11NioProtocol) connector.getProtocolHandler();
			_log.info("MaxConnections={},MaxThreads={},ConnectionTimeout={}", serverConfig.getMaxConnections(),
					serverConfig.getMaxThreads(), serverConfig.getConnectionTimeout());
			// 设置最大连接数
			protocol.setMaxConnections(serverConfig.getMaxConnections());
			// 设置最大线程数
			protocol.setMaxThreads(serverConfig.getMaxThreads());
			// 连接超时 时间
			protocol.setConnectionTimeout(serverConfig.getConnectionTimeout());
			
			_log.info("SniParseLimit={},MinSpareThreads={},EnableLookups={}", serverConfig.getSniParseLimit(),
					serverConfig.getMinSpareThreads(), serverConfig.isEnableLookups());
			protocol.setSniParseLimit(serverConfig.getSniParseLimit());
			protocol.setMinSpareThreads(serverConfig.getMinSpareThreads());
			connector.setEnableLookups(serverConfig.isEnableLookups());
		}
	}
}
